package com.veeder.datacollection.util;

public class DataUtil {
	/**
	 * Convert the given ASCII hex string to a 32-bit IEEE float
	 * 
	 * @param hex
	 *            an ASCII string consisting of hexadecimal letters that is 8
	 *            characters long
	 * @return the equivalent floating-point value
	 */
	public static float hexToFloat(String hex) {
		if (hex.length() != 8)
			throw new IllegalArgumentException(
					"ASCII hex floats must be exactly 8 characters long, given '" + hex + "'");
		int ival = 0;
		for (int i = 0, k = 28; i < hex.length(); ++i, k -= 4) {
			int digit = Character.digit(hex.charAt(i), 16);
			if (digit == -1)
				throw new NumberFormatException("'" + hex.charAt(i) + "' is not a valid hexadecimal character");
			ival |= digit << k;
		}
		return Float.intBitsToFloat(ival);
	}

	/**
	 * Convert the given ASCII hex string to a 64-bit IEEE double
	 * 
	 * @param hex
	 *            an ASCII string consisting of hexadecimal letters that is 16
	 *            characters long
	 * @return the equivalent floating-point value
	 */
	public static double hexToDouble(String hex) {
		if (hex.length() != 16)
			throw new IllegalArgumentException(
					"ASCII hex doubles must be exactly 16 characters long, given '" + hex + "'");
		long ival = 0L;
		for (int i = 0, k = 60; i < hex.length(); ++i, k -= 4) {
			long digit = Character.digit(hex.charAt(i), 16);
			if (digit == -1)
				throw new NumberFormatException("'" + hex.charAt(i) + "' is not a valid hexadecimal character");
			ival |= digit << k;
		}
		return Double.longBitsToDouble(ival);
	}

	/*
	 * *
	 * 
	 * @param floatVal
	 * 
	 * @return
	 */
	public static String floatToHex(float floatVal) {
		String hexIEEE = "00000000";
		int parse = Float.floatToIntBits(floatVal);
		if (parse != 0)
			hexIEEE = Integer.toHexString(parse);
		return hexIEEE;
	}

}
